package com.uzai.console.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;


/**
 * @author liuqi
 * @date 2022年06月08日 17:41
 * @description： Elasticsearch 配置文件
 * <p>
 * SpringBoot 集成 ES 的步骤：
 *  1、导入依赖
 *      https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-getting-started-maven.html
 *  2、编写 ES 配置，给容器中注入一个 RestHighLevelClient，用来操作 9200 端口
 *      https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-getting-started-initialization.html
 *  3、参照官方API
 */
@Configuration
public class ElasticsearchBaseConfig {

    public static final String NAME = "restHighLevelClient";

    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;

    @Bean(name = NAME, destroyMethod = "close")
    @Primary
    public RestHighLevelClient restHighLevelClient() {

        String esUris =  uzaiConsoleSysConfig.getEsBaseUris();
        String[] esUriArr = esUris.split(",");
        HttpHost[] httpHosts = new HttpHost[esUriArr.length];
        for(int i = 0; i< esUriArr.length; i++){
            String[] paras = esUriArr[i].split(":");
            httpHosts[i] = new HttpHost(paras[1].replace("//",""), Integer.valueOf(paras[2]), paras[0]);
        }

        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(uzaiConsoleSysConfig.getEsBaseUsername(), uzaiConsoleSysConfig.getEsBasePassword()));
        RestClientBuilder restClientBuilder = RestClient.builder(httpHosts);
        //配置身份验证
        restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
            @Override
            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }
        });
        return new RestHighLevelClient(restClientBuilder);
    }
}
